﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;

namespace HalkSee.Helper
{
    public class FtpHelper
    {
        public static void UploadFile(FileInfo fileinfo)
        {
            string URI = "ftp://10.6.14.188/" + fileinfo.Name;

            var ftp = (FtpWebRequest)WebRequest.Create(URI);
            //result.Credentials = new System.Net.NetworkCredential(username, password);
            ftp.KeepAlive = false;
            ftp.Method = System.Net.WebRequestMethods.Ftp.UploadFile;
            //指定文件传输的数据类型
            ftp.UseBinary = true;
            ftp.UsePassive = true;
            //告诉ftp文件大小
            ftp.ContentLength = fileinfo.Length;

            //缓冲大小设置为2KB
            const int BufferSize = 2048;
            byte[] content = new byte[BufferSize - 1 + 1];
            int dataRead;
            //打开一个文件流 (System.IO.FileStream) 去读上传的文件
            using FileStream fs = fileinfo.OpenRead();
            try
            {
                //把上传的文件写入流
                using Stream rs = ftp.GetRequestStream();
                do
                {
                    //每次读文件流的2KB
                    dataRead = fs.Read(content, 0, BufferSize);
                    rs.Write(content, 0, dataRead);
                } while (!(dataRead < BufferSize));
                rs.Close();
            }
            catch (Exception ex) 
            { 
            }
            finally
            {
                fs.Close();
            }
        }
    }
}
